<template>
	<view class="add-address">
		<div class="uForm p-2">
			<uni-forms :border-bottom="false" :model="form" ref="uForm" :rules="rules">
				<!-- #ifndef H5 -->
				<view class="selectAddress" @click="clickUniMap">
					选择收货地址
				</view>
				<!-- #endif -->
				<uni-forms-item class="border-bottom" label="收货人" label-width="130" name="name">
					<input v-model="form.name" clearable placeholder="请输入收货人姓名" />
				</uni-forms-item>

				<uni-forms-item class="border-bottom" label="手机号码" label-width="130" name="mobile">
					<input v-model="form.mobile" type="number" maxlength="11" placeholder="请输入收货人手机号码" />
				</uni-forms-item>
				<uni-forms-item class="border-bottom" label="所在区域" label-width="130" name="___path">
					<div class="flex align-center bgf7f7f7 px-2" @click="showPicker" style="height: 36px;">
						{{ form.___path || '请选择所在地区' }}
					</div>
				</uni-forms-item>
				<uni-forms-item class="detailAddress border-bottom" label="详细地址" label-width="130" name="address">
					<input type="textarea" v-model="form.address" maxlength="100" height="150" placeholder="街道楼牌号等" />
				</uni-forms-item>
				<view class="flex align-center">
					<u-checkbox-group shape="circle" size="30">
						<u-checkbox :active-color="lightColor" v-model="form.is_default">设为默认地址</u-checkbox>
					</u-checkbox-group>
				</view>
				<div class="bge87722cc text-center py-1 rounded text-white mt-4" @click="save">
					保存
				</div>
			</uni-forms>

			<m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getpickerParentValue" pickerSize="4">
			</m-city>

			<uniMap v-if="mapFlag" @close="closeMap" @callback="callBackAddress" />
		</div>
	</view>
</template>
<script>
	import {
		addAddress,
		editAddress,
		getAddressList
	} from "@/api/address.js";
	import city from "@/components/m-city/m-city.vue";
	import uniMap from "@/components/uniMap";
	export default {
		components: {
			"m-city": city,
			uniMap,
		},
		data() {
			return {
				lightColor: this.$lightColor, //高亮颜色
				mapFlag: false, // 地图选择开
				routerVal: "",
				form: {
					address: "", //地址详情
					name: "", //收货人姓名
					mobile: "", //手机号码
					consigneeAddressIdPath: [], //地址id
					consigneeAddressPath: [], //地址名字
					___path: "", //所在区域
					is_default: false, //是否默认地址
					province: '',
					city: '',
					district: '',
				},
				// 表单提交校验规则
				rules: {
					name: [{
						required: true,
						message: "收货人姓名不能为空",
						trigger: ["blur", "change"],
					}, ],
					mobile: [{
							required: true,
							message: "手机号码不能为空",
							trigger: ["blur", "change"],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: "手机号码不正确",
							trigger: ["change", "blur"],
						},
					],
					___path: [{
						required: true,
						message: "请选择所在区域",
						trigger: ["change"],
					}, ],
					detail: [{
						required: true,
						message: "请填写详细地址",
						trigger: ["blur", "change"],
					}, ],
				},
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}, ],
			};
		},
		onLoad(option) {
			this.getRegionsById()
			uni.showLoading({
				title: "加载中",
			});
			this.routerVal = option;
			// 如果当前是编辑地址,则需要查询出地址详情信息
			if (option.id) {
				this.getAddressList(option.id)
			}
			uni.hideLoading();
		},
		// 初始化rules必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onShow() {
			// 判断当前系统权限定位是否开启
		},
		methods: {
			// 关闭地图
			closeMap() {
				this.mapFlag = false;
			},
			// 打开地图并访问权限
			clickUniMap() {
				// #ifndef APP-PLUS
				this.mapFlag = true;
				// #endif
			},

			// 如果拒绝权限 提示区设置
			refuseMap() {
				uni.showModal({
					title: "温馨提示",
					content: "您已拒绝定位,请开启",
					confirmText: "去设置",
					success(res) {
						if (res.confirm) {
							//打开授权设置
							// #ifndef MP-WEIXIN
							uni.getSystemInfo({
								success(res) {
									if (res.platform == "ios") {
										//IOS
										plus.runtime.openURL("app-settings://");
									} else if (res.platform == "android") {
										//安卓
										let main = plus.android.runtimeMainActivity();
										let Intent = plus.android.importClass(
											"android.content.Intent"
										);
										let mIntent = new Intent("android.settings.ACTION_SETTINGS");
										main.startActivity(mIntent);
									}
								},
							});
							// #endif
						}
					},
				});
			},
			// 选择地址后数据的回调
			callBackAddress(val) {
				console.log(val)
				uni.showLoading({
					title: "加载中",
				});

				if (val.address_component && val) {
					const address_component = val.address_component
					this.form.address = val.formatted_addresses.recommend; //地址详情
					this.form.province = address_component.province
					this.form.city = address_component.city
					this.form.district = address_component.district
					this.form.___path = `${this.form.province},${this.form.city},${this.form.district},`;
					// this.form.consigneeAddressIdPath = val.data.result.id; // 地址id分割
					// this.form.consigneeAddressPath = val.data.result.name; //地址名称， '，'分割
					// this.form.lat = val.latitude; //纬度
					// this.form.lon = val.longitude; //经度
					uni.hideLoading();
				}

				this.mapFlag = !this.mapFlag; //关闭地图
			},

			// 保存当前 地址
			save() {
				this.$refs.uForm.validate().then(valid => {
					console.log(valid)
					let pages = getCurrentPages(); //获取页面栈
					let beforePage = pages[pages.length - 2]; //上个页面
					console.log(this.form)
					// 如果没有id则为新增地址
					if (Object.keys(valid).some(key => !valid[key])) {
						uni.showToast({
							title: '请完善地址信息',
							icon: 'none'
						})
						return;
					}
					if (!this.form.id) {
						// 删除没有的数据
						delete this.form.___path;
						addAddress({
							...this.form,
							is_default: this.form.is_default ? 1 : 0
						}).then((res) => {
							uni.showToast({
								title: res.msg
							})
							setTimeout(() => {
								uni.navigateBack();
							}, 1500)
						});
					} else {
						// 修改地址
						delete this.form.___path;
						delete this.form.updateBy;
						delete this.form.updateTime;
						editAddress({
							...this.form,
							is_default: this.form.is_default ? 1 : 0
						}).then((res) => {
							uni.showToast({
								title: res.msg
							})
							setTimeout(() => {
								uni.navigateBack();
							}, 1500)
						});
					}
				}).catch(err => {

				});
			},

			// 三级地址联动回调
			getpickerParentValue(e) {
				this.form.consigneeAddressIdPath = [];
				this.form.consigneeAddressPath = [];
				let name = "";
				e.forEach((item, index) => {
					if (item.value) {
						// 遍历数据
						this.form.consigneeAddressIdPath.push(item.value);
						this.form.consigneeAddressPath.push(item.localName);
						if (index == e.length - 1) {
							name += item.localName;
						} else {
							name += item.localName + ",";
						}
					}
				});
				this.form.___path = name;
				const paths = name.split(',')
				console.log(this.form.___path)
				this.form.province = paths[0] || ''
				this.form.city = paths[1] || ''
				this.form.district = paths[2] || ''
			},
			getRegionsById() {
				this.areaTree = uni.getStorageSync('areaTree') || []
			},
			// 显示三级地址联动
			showPicker() {
				this.$refs.cityPicker.show(this.areaTree);
			},
			getAddressList(id) {
				uni.showLoading();
				getAddressList().then((res) => {
					this.addressList = res.data.list;
					console.log(this.addressList);
					const params = this.addressList.find(item => String(item.id) === String(id))
					params.is_default = params.is_default === 1 ? true : false
					params.___path = [params.province, params.city, params.district].join(',');
					console.log(params)
					this.$set(this, "form", params);
					uni.hideLoading()
				});
			},
		}
	};
</script>
<style scoped lang="scss">
	.detailAddress {
		::v-deep .u-form-item--left {
			display: flex;
			align-items: flex-start;
		}
	}

	.saveBtn,
	.selectAddress {
		height: 70rpx;

		line-height: 70rpx;
		text-align: center;
		font-size: 30rpx;
		background: $aider-light-color;
		color: #fff;
		width: 70%;
		margin: 40rpx auto 0 auto;
		border-radius: 20rpx;
	}

	.selectAddress {
		margin-top: 40rpx;
		background: #fff;

		color: $aider-light-color;
		border: 2rpx solid $aider-light-color;
	}

	.uForm {
		width: 94%;
		overflow: hidden;
		left: 3%;
		position: relative;
		top: 2%;
		background: #fff;
		border-radius: 20rpx;
	}

	.add-address {
		width: 100%;
		padding-top: 3%;

		::v-deep .u-form-item {
			background-color: #fff;
			padding: 24rpx 30rpx;
		}

		.u-btn {
			margin: 30rpx 30rpx 0 30rpx;
			background-color: $main-color;
		}

		::v-deep.u-checkbox {
			margin: 30rpx 30rpx 0 30rpx;

			.u-label-class.u-checkbox__label {
				color: $font-color-light;
				font-size: $font-sm;
			}
		}
	}

	::v-deep .u-checkbox__label {
		font-size: 28rpx;
	}
</style>